package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"mei-tuan-tech/cache"
	"mei-tuan-tech/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var good []models.Good
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Debug().Find(&good)
		jsonData, _ := json.Marshal(good)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &good)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表成功",
		"data": good,
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var good []models.Good
	models.DB.Table("goods").Joins("good_user on good_user.id=good.uid").Debug().Where("id=?", id).Find(&good)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表成功",
		"data": good,
	})
}
func Add(c *gin.Context) {
	good_name := c.PostForm("good_name")
	good_types := c.PostForm("good_types")
	data := models.Good{
		GoodName:  good_name,
		GoodTypes: good_types,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
